'use strict';
import moment from 'moment';
import {Button, Form, Input, InputNumber, Modal, notification, Popconfirm, Select, Table, Upload} from 'antd';
import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';

import React from 'react';
import {connect} from 'dva';

import ViewTitle from "../../../components/ViewTitle";
import '../../index.less';
import styles from "../../index.less";
import notify from "../../../components/NotificationExtra";
import ModalSelectProcureMaterialLot from "./xModalSelectProcureMaterialLot";
import FormBase from "../../../components/Base/FormBase";

const table = 'SalesOrder';
const {TextArea} = Input;
moment.locale('zh-cn');
@Form.create()
@connect(({global, sales, dict, store}) => ({...global, ...sales, ...dict, ...store}))
export default class ModalCreateOrEditReplenishmentRecord extends FormBase {
  constructor(props) {
    super(props);
    this.state = undefined;
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
  }

  materialTableCol() {
    return [
      {title: '原料编码', key: 'code', dataIndex: "code"},
      {title: '原料名称', key: 'name', dataIndex: "name"},
      {title: '原料形态', key: 'subcategory', dataIndex: "subcategory"},
      {title: '原料数量', key: 'materialCount', dataIndex: "materialCount"},
      {title: '原料含量%', key: 'materialContent', dataIndex: "materialContent"},
      {
        title: '采购运费', key: 'procureShippingFee', dataIndex: "procureShippingFee"
      },

      {
        title: '成本', key: 'cost', dataIndex: "cost", render: (value, record) => {
          // const {price = 0, materialCount = 0} = record;
          return <div style={{color: '#f22'}}>{value}</div>;
        }
      },
      {
        title: '操作', key: 'opt', dataIndex: "opt", render: (value, record) => {
          return <span>
            <a style={{marginRight: '6px'}}
               onClick={() => {
                 const {addMaterials} = this.state;

                 ModalView.open(ModalSelectProcureMaterialLot, {
                   title: '编辑原料',
                   width: '1580px',
                   maskClosable: false
                 }, {
                   record,
                   isEdit: true,
                   callback: (data) => {
                     console.log('dataaa',data)
                     _.remove(addMaterials, item => {
                       return item.usedLotId === record.usedLotId;
                     });
                     addMaterials.unshift(data);
                     const temp = this.state;
                     temp.addMaterials = addMaterials;
                     this.setState({...temp});
                   }
                 });
               }}
            >编辑</a>
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                const {addMaterials} = this.state;
                _.remove(addMaterials, item => {
                  return item.usedLotId === record.usedLotId;
                });
                const temp = this.state;
                temp.addMaterials = addMaterials;
                this.setState({...temp});
              }}
              okText="是"
              cancelText="否"
            >
              <a style={{marginRight: '6px'}}>删除</a>
            </Popconfirm>}
            </span>;
        }
      }
    ];
  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              const {addMaterials = [], fileList = []} = this.state;
              if (fileList.length === 0) {
                notify({type: 'error', message: "请上传包装标识"});
                return;
              }
              values.materials = addMaterials;
              values.fileList = fileList;
              callback(values);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  picHandleCancel = () => this.setState({previewVisible: false});

  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    const temp = this.state;

    temp['previewImage'] = file.url || file.preview;
    temp['previewVisible'] = true;
    this.setState({...temp});
  };

  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };

  render() {
    const {form, values, cols = 3} = this.props;
    if (this.state === undefined || this.state === null) {
      this.state = {...values};
      this.state.addMaterials = values && values.materials ? values.materials : [];
    }
    const {previewVisible, previewImage, fileList = []} = this.state;
    const model = this.props[`${table}Model`];
    if (!model) return<div></div>;

    const {
      prodName,
      prodCode,
      price = 0,
      pkgFee = 0,
      laborFee = 0,
      taxDeductionPointForLaborCosts = 0,
      invoicingDate,
      deliverWay,

      count = 0,
      label,
      pkg,
      addMaterials = []
    } = this.state;

    return (
      <div>
        <FormLayout form={form} cols={cols}>
          <FormField
            label={'品名'}
            name={'prodName'}
            required={true}
            initialValue={prodName}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'编号'}
            name={'prodCode'}
            required={true}
            initialValue={prodCode}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'数量'}
            name={'count'}
            required={true}
            initialValue={count}
          >
            <InputNumber  style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'售价'}
            name={'price'}
            required={true}
            initialValue={price}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'标签'}
            name={'label'} initialValue={label}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装'}
            name={'pkg'} initialValue={pkg}
          >
            <Input style={{width: '100%'}}></Input>
          </FormField>
          <FormField
            label={'包装费用'}
            name={'pkgFee'} initialValue={pkgFee}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'项目奖励'}
            name={'laborFee'}
            initialValue={laborFee}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'劳务扣税点'}
            name={'taxDeductionPointForLaborCosts'}
            initialValue={taxDeductionPointForLaborCosts}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'发货方式'}
            name={'deliverWay'} initialValue={deliverWay}
          >
            <Select style={{width: '100%'}}>
              {this.getSelectOption(model && model.deliverWay ? model.deliverWay.options : [])}
            </Select>
          </FormField>
        </FormLayout>
        <ViewTitle
          title={'原料信息'}
          actions={[

            <Button type={'primary'} onClick={() => {
              const {count = 0} = form.getFieldsValue();
              if (count === 0) {
                notify({type: 'warning', message: "请输入重量(KG)"});
                return;
              }
              ModalView.open(ModalSelectProcureMaterialLot, {
                title: '选择采购原料批次',
                width: '1580px',
                maskClosable: false
              }, {
                record:{count},
                callback: (data) => {
                  data.usedLotId = "ULD" + new Date().valueOf();
                  addMaterials.push(data);
                  const temp = this.state;
                  temp.addMaterials = addMaterials;
                  this.setState({...temp});
                }
              });
            }}>选择采购原料批次</Button>
          ]
          }
        ></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.materialTableCol()}
          dataSource={addMaterials}
          scroll={{x: true}}
          pagination={true}
        ></Table>

        <ViewTitle
          title={'包装标识'}
        ></ViewTitle>

        <div style={{marginLeft: '64px'}}>
          <Upload
            action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
            listType="picture-card"
            fileList={fileList}
            accept={".png,.jpg"}
            onPreview={this.picHandlePreview}
            onChange={this.picHandleChange}
            onDownload={file => {
              console.log('ondownlad', file);
            }}
            beforeUpload={(file, fileList) => {
              const isLt2M = file.size / 1024 / 1024 < 2;
              console.log('file size', file.size, isLt2M);
              if (!isLt2M) {
                notify({type: 'error', message: '文件过大！'});
                return isLt2M;
              }
              return false;
            }}
          >
            {this.getUploadPicButton()}
          </Upload>
          <Modal visible={previewVisible} footer={null} onCancel={this.picHandleCancel}>
            <img alt="example" style={{width: '100%'}} src={previewImage}/>
          </Modal>
        </div>

        {
          this.renderFoot()
        }
      </div>

    );
  }
}
